<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            v-model="queryInfo.query"
            placeholder="请输入用户姓名"
            class="input-with-select"
            @keyup.enter.native="getUserList()"
            clearable
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true ">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" fixed></el-table-column>
        <el-table-column label="姓名">
          <template #default="scope">{{ scope.row.username }}</template>
        </el-table-column>
        <el-table-column label="邮箱">
          <template #default="scope">{{ scope.row.email }}</template>
        </el-table-column>
        <el-table-column label="电话">
          <template #default="scope">{{ scope.row.mobile }}</template>
        </el-table-column>
        <el-table-column label="角色">
          <template #default="scope">{{ scope.row.role_name }}</template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        
        <el-table-column fixed="right" label="操作" width="240">
          <template #default="scope">
            <el-button type="primary" size="small" @click="showEditDialog(scope.row.id)"> 修改 </el-button>
            <el-button type="danger" size="small" @click="removeUserById(scope.row.id)"> 删除 </el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button type="warning" size="small" @click="setUserRole(scope.row)"> 设置 </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分区域 -->
      <el-pagination
        v-model:currentPage="queryInfo.pagenum"
        v-model:page-size="queryInfo.pagesize"
        :page-sizes="[1, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加用户" width="30%" center @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名:" prop="username" >
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password" >
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email" >
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile" >
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addUser">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog v-model="editDialogVisible" title="修改用户" width="30%" center @close="editDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名:" prop="username" >
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email" >
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile" >
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editUser">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog 
      v-model="setRoleDialogVisible" 
      title="角色分配" 
      width="30%" 
      center 
      @close="setRoleDialogClosed"
    >
      <!-- 内容主体区域 -->
      <div>
        <p>当前的用户: {{ userInfo.username }}</p>
        <p>当前的角色: {{ userInfo.role_name }}</p>
        <p>分配新角色：
           <el-select v-model="seclectRoleId" class="m-2" placeholder="请选择">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              />
            </el-select>
        </p>
      </div>
     
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setRoleDialogClosed">取消</el-button>
          <el-button type="primary" @click="saveRoleInfo">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from '../../http/axios.js'

export default {
  name: 'User',
  data() {
    // 邮箱验证规则
    const checkEmail = (rules,value,callback) => {
      let regEmail = /^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;

      if(regEmail.test(value)){
        return callback();
      }else{
        callback(new Error('请输入合法的邮箱'));
      }
    }

    return {
      checkEmail,
      queryInfo: {
        query: '',
        pagenum: 1, // 当前页数
        pagesize: 10,
      },
      total: 0,
      userList: [],
      addDialogVisible: false, //控制添加用户对话框的显示与隐藏
      editDialogVisible: false, //控制添修改户对话框的显示与隐藏
      addForm: { // 添加用户的表单数据
        username: '',
        password: '',
        email: '',
        mobile: ''
      }, 
      addFormRules: { // 添加表单验证规则的对象
        username: [
          {
            required: true,
            message: '用户名不能为空',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 10,
            message: '用户名需要是3-10字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '密码不能为空',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 16,
            message: '密码是6-16位字符组合',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '邮箱不能为空',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '手机号不能为空',
            trigger: 'blur'
          },
          {
            pattern: /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/,
            message: '手机号输入错误',
            trigger: 'blur'
          }
        ]
      },
      editFormRules: { // 添加修改员工数据验证规则的对象
        email: [
          {
            required: true,
            message: '邮箱不能为空',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '手机号不能为空',
            trigger: 'blur'
          },
          {
            pattern: /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/,
            message: '手机号输入错误',
            trigger: 'blur'
          }
        ]
      },
      editForm: {},//当前修改对象数据
      setRoleDialogVisible: false, // 控制角色分配对话框的显示与隐藏
      userInfo: {}, // 当前正在分配角色的对象信息
      roleList: [], // 角色列表信息
      seclectRoleId: '' , // 已选中角色的id
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await axios.get('users', { params: this.queryInfo })

      if (res.meta.status !== 200) {
        this.$message({
          type: 'error',
          message: '获取用户列表失败',
        })
      } else {
        this.total = res.data.total
        this.userList = res.data.users
      }
    },
    handleDelete() {},
    // 监听 pageSize 改变事件
    handleSizeChange(newPageSize) {
      this.queryInfo.pagesize = newPageSize
      this.getUserList()
    },
    // 监听 页码值的变化
    handleCurrentChange(newPageNum) {
      this.queryInfo.pagenum = newPageNum
      this.getUserList()
    },
    // 监听switch 开关状态的改变
    async userStateChanged(userInfo) {
      const { data: res } = await axios.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )

      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state

        return this.$message({
          type: 'error',
          message: '用户状态更新失败',
        })
      } else {
        return this.$message({
          type: 'success',
          message: '用户状态更新成功',
        })
      }
    },
    // 监听添加用户对话框的关闭按钮
    addDialogClosed(){
      this.$refs.addFormRef.resetFields();
    },
    // 监听修改用户对话框的关闭按钮
    editDialogClosed(){
      this.$refs.editFormRef.resetFields();
    },
    // 点击按钮添加用户
    addUser(){
      this.$refs.addFormRef.validate(async (valid) => {
        if(!valid){
          return ;
        }else{
          const { data: res} = await axios.post('users',this.addForm);

          if(res.meta.status !== 201 ){
            this.$message({
              type: 'error',
              message: '用户添加失败'
            })
          }else{
            this.$message({
              type: 'success',
              message: '用户添加成功'
            })

            this.addDialogVisible = false;
            this.getUserList();
          }
        }
      })
    },
    // 点击按钮修改用户
    editUser(){
      this.$refs.editFormRef.validate(async (valid) => {
        if(!valid){
          return ;
        }else{
          const { data: res} = await axios.put('users/' + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          });
 
          if(res.meta.status !== 200){
            this.$message({
              type: 'error',
              message: res.meta.status 
            })
          }else{
            this.$message({
              type: 'success',
              message: '数据' + res.meta.msg
            })
          };
          
          this.editDialogClosed();
          this.editDialogVisible = false;
          this.getUserList();
        }
      })
    },
    async showEditDialog(userid){ 
     
      const { data: res } = await axios.get('users/' + userid);

      if(res.meta.status !== 200){
        this.$message({
          type: 'error',
          message: '获取该用户信息错误'
        })
      }

      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    removeUserById(userId){ // 删除用户
      this.$messageBox.confirm("该操作会永久删除该用户信息",'删除用户',{
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {

        const { data: res } = await axios.delete('users/' + userId);

        if(res.meta.status !== 200){
          this.$message({
            type: 'error',
            message: '删除失败'
          })
        }else{
          this.$message({
            type: 'success',
            message: '删除成功'
          });
          this.getUserList();
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })
    },
    async setUserRole(userInfo){ // 点击角色分配按钮
      this.userInfo = userInfo;
      const { data: res} = await axios.get('roles');

      if(res.meta.status !== 200){
        this.$message({
          type: 'error',
          message: '获取角色列表失败'
        })
      }else{
        this.roleList = res.data;
      }

      this.setRoleDialogVisible = true;
    },
    setRoleDialogClosed(){ // 关闭当前角色分配按钮
      this.userInfo = {};
      this.setRoleDialogVisible = false;
    },
    async saveRoleInfo(){ // 点击按钮分配用户角色
      if(!this.seclectRoleId){
        return this.$message({
          type: 'error',
          message: '请选择要分配的角色'
        });
      }
      const { data: res} = await axios.put(`users/${this.userInfo.id}/role`,{ rid: this.seclectRoleId});

      if(res.meta.status !== 200){
        this.$message({
          type: 'error',
          message: '设置用户角色失败'
        })
      }else{
        this.$message({
          type: 'success',
          message: '设置用户新角色成功'
        });
        this.getUserList();
        this.setRoleDialogClosed();
      }

    }
  },
}
</script>

<style>
</style>